package temporaryCache

import (
	"context"
	"encoding/json"
	"time"
)

// 添加哈希缓存
func (c temporaryCache) HashCacheAddMultiple(key string, value map[string]interface{}, cacheTtl, lockTtl time.Duration, requestId int, ctx context.Context) (err error) {
	var (
		tx      = c.redis.TxPipeline()
		command = make(map[string]interface{})
	)
	// 等待锁释放
	err = c.WaitLock(ctx, key)
	if err != nil {
		return err
	}
	// 添加锁
	_, err = c.TryLock(key, requestId, lockTtl, ctx)
	if err != nil {
		return err
	}
	for k, v := range value {
		js, err := json.Marshal(v)
		if err != nil {
			return err
		}
		command[k] = js
	}
	tx.HMSet(ctx, key, command)
	tx.Expire(ctx, key, cacheTtl)
	_, err = tx.Exec(ctx)
	if err != nil {
		tx.Discard()
	}
	// 解锁
	err = c.UnLock(ctx, key, requestId)
	return err
}

// 获取哈希所有key
func (c temporaryCache) HashCacheGetAllKey(key string, ctx context.Context) (keyExist bool, result []string, err error) {
	exist, err := c.Exist(key, ctx)
	if err != nil || !exist {
		return false, nil, err
	}
	// 获取数据
	result, err = c.redis.HKeys(ctx, key).Result()
	return
}

// 获取哈希单条key
func (c temporaryCache) HashCacheGet(key, hashKey string, ctx context.Context) (keyExist bool, result []byte, err error) {
	exist, err := c.Exist(key, ctx)
	if err != nil || !exist {
		return false, nil, err
	}
	result, err = c.redis.HGet(ctx, key, hashKey).Bytes()
	return
}
